package com.tsd.base.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.base.entity.BaseRelatedParty;
import com.tsd.base.entity.BaseRelatedPartyExt;
import com.tsd.base.service.BaseRelatedPartyService;
import com.tsd.common.controller.BaseController;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.system.entity.SysUser;
import com.tsd.system.service.SystemSettingService;
import com.tsd.system.vo.GlobalSetting;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：BaseRelatedParty往来单位 控制层
 *
 * @author david
 * @date 2024/03/26 15:24:49
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
@Api(tags = "系统资料-往来单位", description = "往来单位的API描述")
public class BaseRelatedPartyController extends BaseController {

    @Resource
    private BaseRelatedPartyService baseRelatedPartyService;
    @Resource
    private SystemSettingService systemSettingService;


    @ApiOperation(value = "根据sid获取往来单位", notes = "根据sid获取往来单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sid", value = "往来单位sid", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/getBaseRelatedPartyBySid.action", method = RequestMethod.POST)
    public HttpResult<Object> getBaseRelatedPartyBySid() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            String sid = HlpUtils.getString(map, "sid");
            super.checkEmpty(sid, "请提供参数sid");
            BaseRelatedParty baseRelatedParty = baseRelatedPartyService.queryBySid(sid);
            hr.setData(baseRelatedParty);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除往来单位", notes = "根据id删除往来单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sids", value = "往来单位sids", required = true, dataType = "string", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/deleteBaseRelatedPartys.action", method = RequestMethod.POST)
    public HttpResult<Object> deleteBaseRelatedPartys() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Object sids = map.get("sids");
            super.checkEmpty(sids, "请提供参数sids");
            List<String> list = JSON.parseArray(JSON.toJSONString(sids), String.class);
            baseRelatedPartyService.deleteBaseRelatedPartys(list, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }


    @ApiOperation(value = "保存往来单位", notes = "保存往来单位，具有id值则更新，没有id值则新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "obj", value = "往来单位", required = true, paramType = "body", dataType = "BaseRelatedParty")
    })
    @ResponseBody
    @RequestMapping(value = "/saveBaseRelatedParty.action", method = RequestMethod.POST)
    public HttpResult<Object> saveBaseRelatedParty() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            SysUser opUser = super.getSysUser();
            BaseRelatedPartyExt partyExt = super.getParams(request, BaseRelatedPartyExt.class);
            baseRelatedPartyService.saveBaseRelatedParty(partyExt, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询往来单位", notes = "分页查询往来单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findBaseRelatedPartys.action", method = RequestMethod.POST)
    public HttpResult<Object> findBaseRelatedPartys() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyListValue(map, params, "rec_type_list", "rec_type_list", false, Integer.class);
            hr = findBody(map, params);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询往来单位", notes = "分页查询往来单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findSysClients.action", method = RequestMethod.POST)
    public HttpResult<Object> findSysClients() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = super.getDataPermissionParams();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            List<Integer> clientTypeList = new ArrayList<>();
            clientTypeList.add(BaseRelatedPartyExt.REC_TYPE_CLIENT);
            clientTypeList.add(BaseRelatedPartyExt.REC_TYPE_CLIENT_SUPPLIER);
            params.put("rec_type_list", clientTypeList);
            if (map.containsKey("tree")) {
                List<BaseRelatedPartyExt> list = baseRelatedPartyService.findBaseRelatedPartyTypeTreeWithChildren(params);
                hr.setData(list);
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                params.put("is_group", 0);
                hr = findBody(map, params);
            }
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询往来单位", notes = "分页查询往来单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "pageNo", value = "页码", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageSize", value = "页大小，每页记录数", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "sorts", value = "排序设置，方式['property1 desc','property2']", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "totalRows", value = "总记录数，为了减少统计总记录数，一般从第二页开始前端提供totalRows", required = false, dataType = "int", paramType = "form")
    })
    @ResponseBody
    @RequestMapping(value = "/findSysSuppliers.action", method = RequestMethod.POST)
    public HttpResult<Object> findSysSuppliers() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            List<Integer> clientTypeList = new ArrayList<>();
            clientTypeList.add(BaseRelatedPartyExt.REC_TYPE_SUPPLIER);
            clientTypeList.add(BaseRelatedPartyExt.REC_TYPE_CLIENT_SUPPLIER);
            params.put("rec_type_list", clientTypeList);
            if (map.containsKey("tree")) {
                List<BaseRelatedPartyExt> list = baseRelatedPartyService.findBaseRelatedPartyTypeTreeWithChildren(params);
                hr.setData(list);
                hr.setCode(ErrorCode.CODE_SUCCESS);
            } else {
                params.put("is_group", 0);
                hr = findBody(map, params);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    private HttpResult<Object> findBody(Map<String, Object> map, Map<String, Object> params) {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "parent_sid", "parent_sid", false, false);
            HlpUtils.copyIntegerValue(map, params, "state", "state", false, 1);
            HlpUtils.copyStringValue(map, params, "name", "name", false, false);
            HlpUtils.copyStringValue(map, params, "linker_name", "linker_name", false, false);
            HlpUtils.copyStringValue(map, params, "linker_mobile", "linker_mobile", false, false);
            HlpUtils.copyStringValue(map, params, "search_value", "search_value", false, true);
            HlpUtils.copyStringValue(map, params, "selected_value", "selected_value", false, false);
            HlpUtils.copyIntegerValue(map, params, "is_group", "is_group", false, null);
            PageBean page = new PageBean(map).procNoPage(map);
            List<BaseRelatedPartyExt> list = baseRelatedPartyService.findBaseRelatedPartys(params, page);
            if (!HlpUtils.isEmptyList(list)) {
                GlobalSetting setting = systemSettingService.getGlobalSetting();
                if (map.containsKey("filter_global")) {
                    ListUtil.forEach(list, setting::procRelatedPartyDisplayBase);
                }
            }
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 查询往来单位分类树
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findBaseRelatedPartyTypeTree.action", method = RequestMethod.POST)
    public HttpResult<Object> findBaseRelatedPartyTypeTree() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>(2);
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "parent_sid", "parent_sid", false, false);
            List<BaseRelatedPartyExt> list = baseRelatedPartyService.findBaseRelatedPartyTypeTree(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 查询往来单位分组树(含单位)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findBaseRelatedPartyTypeTreeWithChildren.action", method = RequestMethod.POST)
    public HttpResult<Object> findBaseRelatedPartyTypeTreeWithChildren() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<>();
            HlpUtils.copyIntegerValue(map, params, "dr", "dr", false, 0);
            HlpUtils.copyStringValue(map, params, "parent_sid", "parent_sid", false, false);
            List<BaseRelatedPartyExt> list = baseRelatedPartyService.findBaseRelatedPartyTypeTreeWithChildren(params);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    /**
     * 导入往来单位基本资料
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/importBaseRelatedParty.action", method = RequestMethod.POST)
    public HttpResult<Object> importBaseRelatedParty() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser opUser = super.getSysUser();
            Object list = map.get("list");
            super.checkEmpty(list, "缺少参数list");
            String json = JSON.toJSONString(list);
            List<BaseRelatedPartyExt> clientList = JSON.parseArray(json, BaseRelatedPartyExt.class);
            //名称为空，则跳过
            List<BaseRelatedPartyExt> filters = ListUtil.filter(clientList, t -> !HlpUtils.isEmpty(t.getName()));
            baseRelatedPartyService.importBaseRelatedPartys(filters, opUser);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

}
